class DocumentCategory < ActiveRecord::Base 
  has_many(:document, :dependent => :destroy, :order => "title")
  has_and_belongs_to_many(:page)
  has_and_belongs_to_many(:user_group)

  validates_presence_of(:name,:title,:updated_by)

  validates_format_of(:name, :with => %r{^([-_.A-Za-z0-9\s]*)$})

  def directory_name
    t = name.gsub(/\'/,'')
    t.gsub(/[^\w\.\-]/,'_')
  end

  def has_page?(pid)
    return false if pid.nil?
    page.each{|pg| return true if pg.id == pid }
    return false
  end

  def total_kilobytes
    rvalue = DocumentVersion.connection.execute("SELECT sum(dv.kilobytes) from documents ds, document_versions dv where ds.document_category_id = #{self.id} and dv.document_id = ds.id")
    rvalue.result.to_s.to_i
  end
end
